<?php

ob_start();

require_once("inc/user_auth.inc");
require_once("inc/getsets.inc");

$subError = null;
$problemId = submitProblem($subError);

if ($problemId)
{	// redirect to the status page for the newly submitted problem
	header("Location: http://elm.cis.uncw.edu/ddas/submit/check-status.php?problemId=$problemId");
	ob_end_flush();
}
else
{	// redirect to an error page showing the error text
	header("Location: http://elm.cis.uncw.edu/ddas/submit/show-error.php?error=$subError");
	ob_end_flush();
}

function submitProblem(&$subError)
{
	$userId = getSessionVariable("userId");

	$file = getFormFile("csv");

	$numRows = getFormVariable("numRows");
	$numColX = getFormVariable("numColX");
	$numColY = getFormVariable("numColY");
	$numResults = getFormVariable("numResults");
	
	if (!$userId) 
	{	
		$subError = "Variable userId was not found.";
		return 0; 
	}

	if (!$file) 
	{ 
		$subError = "File upload failed.";
		return 0;
	}
	
	if ($subError = testCSVStructure($file["tmp_name"], $numRows, $numColX + $numColY))
	{	// some error occured while checking csv file structure
		return 0;
	}
	
	$problemId = sqlInsertProblem($userId, $numRows, $numColX, $numColY, $numResults);
	$path = "/home/boinc/projects/ddas/problem";
	$location = "$path/$problemId.csv";
	
	if (!$problemId)
	{
		$subError = "Failed to create problem record in mysql table.";
		return 0;
	}
	
	if (!putFileOnServer($file, $location, 0666))
	{
		$subError = "File upload and/or copy failed.";
		return 0;
	}
	
	return $problemId;
}

/*
* Put a file on the server in the specified location.
*/
function putFileOnServer($file, $location, $mode)
{
	if ($file && $location && $mode)
	{
		if (move_uploaded_file($file["tmp_name"], $location))
		{
			chmod($location, $mode);
			return true;
		}
	}
	
	return false;
}

/*
* Test the structure of the CSV file.
*/
function testCSVStructure($file, $rows, $columns)
{
	$handle = @fopen($file, 'r');

	if ($handle)
	{
		$row = 0;

		while(!feof($handle))
		{
			$row++;

			$line = fgets($handle, 4096);
			$colsPerLine = substr_count($line, ',') + 1;

			if ($colsPerLine != $columns)
			{	// the number of columns is not correct
				return "Invalid column count on row $row.  Found $colsPerLine columns.";
			}

			if (substr_count($line, ' ') > 0)
			{	// the file contains one or more spaces
				return "Invalid character (space) found on row $row.";
			}
		}

		if ($row != $rows)
		{	// invalid number of rows in file
			return "Invalid row count: Found $row rows.";
		}
	}

	fclose($handle);

	// file structure ok
	return "";
}

?>